import React, { Component, useState, useEffect } from 'react';
import EditTemplate from '@/components/EditTemplate';
import { connect } from 'dva';
import md5 from 'js-md5';
const UserInfo = ({ dispatch, userInfo }) => {
  const filters = [
    {
      title: '项目信息',
      list: [
        {
          key: 'currentPassword',
          type: 'password',
          span: 24,
          label: '当前密码',
          rules: [{ required: true, message: '请输入当前密码' }],
        },
        {
          key: 'newPassword',
          type: 'password',
          span: 24,
          label: '新密码',
          rules: [{ required: true, message: '请输入新密码' }],
        },
        {
          key: 'checkPassword',
          type: 'password',
          span: 24,
          label: '重复新密码',
          rules: [
            { required: true, message: '请输入当前密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次密码不一致!'));
              },
            }),
          ],
        },
      ],
    },
  ];
  const saveUrl = '/api/account/v1/updatePassword';
  const onSave = () => {
    dispatch({
      type: '$msg/showToast',
      payload: {
        title: '请重新登录！',
        type: 'success',
      },
    });
    dispatch({ type: 'auth/logout' });
  };
  const preproccess = data => {
    if (!userInfo) userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
    return {
      uuid: userInfo.uuid,
      oldPassword: md5(data.currentPassword),
      newPassword: md5(data.newPassword),
    };
  };
  return (
    <div>
      <EditTemplate
        preproccess={preproccess}
        filters={filters}
        updateUrl={saveUrl}
        onSave={onSave}
      />
    </div>
  );
};
export default connect(state => state.auth)(UserInfo);
